<template>
  <div class="container">
    <!-- 添加 Loading 组件 -->
    <Loading v-if="isLoading" />
    <!-- 顶部导航区域 -->
    <div class="nav-container">
      <h2 class="page-title">账单明细</h2>
      <router-link to="/statistics" class="stats-button">
        <span>统计分析</span>
        <span class="icon">📊</span>
      </router-link>
    </div>
    
    <!-- 日历区域 -->
    <div class="calendar-container card">
      <MyCalendar 
        :formatter="formatter" 
        :initialYear="currentYear"
        :initialMonth="currentMonth"
        @daySelected="handleDaySelected" 
        @monthChanged="handleMonthChanged" 
      />
    </div>

    <!-- 账单详情区域（仅在选中日期后显示） -->
    <div class="bill-container card" v-if="selectedDate">
      <div class="date-header">
        <span class="date-text">{{ selectedDate }}</span>
        <span class="total">
          总计: {{ formatAmount(totalForSelected) }}
        </span>
      </div>

      <div v-if="filteredBills.length">
        <!-- Vant SwipeCell 组件 -->
        <van-swipe-cell v-for="bill in filteredBills" :key="bill.id" :right-width="100">
          <template #default>
            <div class="bill-item">
              <div class="icon">{{ getIcon(bill.category) }}</div>
              <div class="bill-info">
                <span class="category">{{ bill.category }}</span>
                <span class="note">{{ bill.remark }}</span>
              </div>
              <span class="amount" :class="{ income: bill.amount > 0 }">
                {{ formatAmount(bill.amount) }}
              </span>
            </div>
          </template>
          <template #right>
            <div class="button-group">
              <div class="edit-button" @click.stop="openEditModal(bill)">编辑</div>
              <div class="delete-button" @click.stop="handleDelete(bill.id)">删除</div>
            </div>
          </template>
        </van-swipe-cell>
      </div>
      <div v-else class="no-bill">
        <p>该日期暂无账单记录</p>
      </div>
    </div>

    <!-- 编辑账单 Modal -->
    <Modal :visible="isEditModalVisible" title="编辑账单" @confirm="handleEditConfirm" @cancel="closeEditModal">
      <div class="edit-form">
        <div class="form-item">
          <label>日期：</label>
          <input type="date" v-model="editingBill.date" class="input-box" />
        </div>
        <div class="form-item">
          <label>金额：</label>
          <input type="number" v-model.number="editingBill.amount" class="input-box" />
        </div>
        <div class="form-item">
          <label>类别：</label>
          <div class="category-selector">
            <button
              v-for="category in categories"
              :key="category.name"
              @click="editingBill.category = category.name"
              class="category-select-btn"
              :class="{ active: editingBill.category === category.name }"
            >
              <span class="category-icon-small">{{ category.icon }}</span>
              <span class="category-name-small">{{ category.name }}</span>
            </button>
          </div>
        </div>
        <div class="form-item">
          <label>备注：</label>
          <input type="text" v-model="editingBill.remark" class="input-box" />
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import MyCalendar from "../../components/MyCalendar/MyCalendar.vue";
import { SwipeCell } from "vant";
import Modal from "../../components/Modal/Modal.vue";
import Loading from "../../components/Loading/Loading.vue"; // 导入 Loading 组件
import { useBillListPage } from "./BillListPage";
import { updateBill } from "../../api/modules/bill.api";

interface Bill {
  date: string;
  amount: number;
  category: string;
  remark: string;
  id: number;
}

const {
  formatter,
  categories, // 类别列表
  selectedDate,
  handleDaySelected,
  filteredBills,
  totalForSelected,
  getIcon,
  fetchBills,
  deleteBill,
  isLoading, // 获取 isLoading 状态
  handleMonthChanged, // 月份变化处理函数
  currentYear, // 当前年份
  currentMonth, // 当前月份
} = useBillListPage();

const isEditModalVisible = ref(false);
const editingBill = ref<Bill>({
  id: 0,
  date: "",
  amount: 0,
  category: "",
  remark: "",
});

// 打开编辑模态框
const openEditModal = (bill: Bill) => {
  editingBill.value = { ...bill };
  isEditModalVisible.value = true;
};

// 关闭编辑模态框
const closeEditModal = () => {
  isEditModalVisible.value = false;
};

// 确认编辑账单
const handleEditConfirm = async () => {
  try {
    await updateBill(editingBill.value);
    const index = filteredBills.value.findIndex(b => b.id === editingBill.value.id);
    if (index !== -1) {
      filteredBills.value[index] = { ...editingBill.value };
    }
    isEditModalVisible.value = false;
  } catch (error) {
    console.error("更新账单失败：", error);
  }
};

// 删除账单
const handleDelete = async (billId: number) => {
  await deleteBill(billId);
};

// 统一金额格式化
const formatAmount = (amount: number) => {
  return amount > 0 ? `+ ¥${Math.abs(amount).toFixed(2)}` : `- ¥${Math.abs(amount).toFixed(2)}`;
};
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 10px;
}

.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: relative;
  border: 2px solid transparent;
}

.calendar-container,
.bill-container {
  padding: 15px 20px;
}

.date-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: var(--text-color, #333);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  font-size: 16px;
  font-weight: bold;
  color: var(--primary-color, #FF7E92);
}

.bill-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 12px;
}

.icon {
  width: 44px;
  height: 44px;
  background: var(--primary-gradient);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  margin-right: 12px;
}

.bill-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.category {
  font-size: 16px;
  font-weight: bold;
  color: var(--text-color, #333);
}

.note {
  font-size: 14px;
  color: #777;
}

.amount {
  font-size: 16px;
  font-weight: bold;
  color: #d9534f;
}

.amount.income {
  color: #28a745;
}

.button-group {
  display: flex;
  height: 100%;
  width: 100px;
}

.button-group > div {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #fff;
  cursor: pointer;
  transition: background 0.2s ease-in-out;
}

.edit-button {
  background-color: #3498db;
}

.delete-button {
  background-color: #e74c3c;
  border-radius: 0 8px 8px 0;
}

.edit-button:hover {
  background-color: #2980b9;
}

.delete-button:hover {
  background-color: #c0392b;
}

.no-bill p {
  text-align: center;
  color: #777;
  margin: 10px 0;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.edit-form .form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.edit-form .form-item label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.input-box {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 类别选择器样式 */
.category-selector {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  width: 100%;
}

.category-select-btn {
  flex: 1;
  min-width: calc(50% - 4px);
  padding: 10px 8px;
  background: #f5f5f5;
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s;
}

.category-select-btn:hover {
  background: #e8e8e8;
}

.category-select-btn.active {
  background: linear-gradient(135deg, #ffe1e1, #e1f3ff);
  border: 2px solid;
  border-image: var(--primary-gradient) 1;
  font-weight: 600;
}

.category-icon-small {
  font-size: 18px;
}

.category-name-small {
  font-size: 14px;
}

.nav-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  width: 100%;
}

.page-title {
  margin: 0;
  color: var(--text-color);
}

.stats-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 12px;
  background: var(--primary-gradient);
  color: white;
  border-radius: 6px;
  text-decoration: none;
  font-weight: 500;
  transition: background 0.3s;
}

.stats-button:hover {
  background: var(--primary-gradient-hover);
}

.stats-button .icon {
  font-size: 18px;
}

</style>